﻿#pragma warning(disable:4005)
#include <drogon/HttpController.h>
#include "OCMain/Environment.h"
#include "OCMain/FileUtil.h"
#include "OCServer/DocGenerate.h"
#include "ProjectTimer.h"
#include "apiDoc.h"

using namespace drogon;
using namespace OCPP;

inline void setGZIp(HttpResponsePtr& resp)
{
	resp->addHeader("Content-Encoding", "gzip");
}

class MicroWin3dService : public HttpController<MicroWin3dService>
{
public:
	METHOD_LIST_BEGIN
		METHOD_ADD(MicroWin3dService::home, "", Get);
		METHOD_ADD(MyDoc::doc, "/doc?query={}", Get);
		METHOD_ADD(MicroWin3dService::getFile, "/getFile?time={time}&region={region}", Get);
		METHOD_ADD(MicroWin3dService::getTimeList, "/getTimeList?startTime={startTime}&endTime={endTime}", Get);
	METHOD_LIST_END
protected:
	void home(const HttpRequestPtr& req,
		std::function<void(const HttpResponsePtr&)>&& callback)
	{
		auto resp = drogon::HttpResponse::newHttpResponse();
		resp->setBody(String("<p>MicroWin3dService</p>"));
		callback(resp);
	}

	void doc(const HttpRequestPtr& req,
		std::function<void(const HttpResponsePtr&)>&& callback,
		String queryapi)
	{
		String docClass = "MicroWin3dService";
		if (queryapi == "")
		{
			auto resp = drogon::HttpResponse::newRedirectionResponse("/swagger/index.html?s=" + docClass);
			callback(resp);
		}
		else
		{
			auto resp = HttpResponse::newNotFoundResponse();
			callback(resp);
		}
	}

	void getTimeList(const HttpRequestPtr& req,
		std::function<void(const HttpResponsePtr&)>&& callback,
		String startTime, String endTime)
	{
		auto resp = HttpResponse::newHttpResponse();
		auto timeVec = Singleton(ProjectTimer).query(startTime, endTime);

		if (timeVec.empty())
		{
			resp->setBody("[]");
		}
		else
		{
			Json::Value value;
			for (const auto& time : timeVec)
			{
				value.append(time);
			}
			resp->setBody(value.toStyledString());
		}

		callback(resp);
	}

	void getFile(const HttpRequestPtr& req,
		std::function<void(const HttpResponsePtr&)>&& callback,
		String time, String region)
	{
		auto resp = HttpResponse::newHttpResponse();
		String gzContent = Singleton(ProjectTimer).getFile(time, region);
		size_t size = gzContent.size();
		if (size != 0)
		{
			resp = drogon::HttpResponse::newFileResponse((const unsigned char*)gzContent.data(), size, time + ".bin",
				CT_APPLICATION_OCTET_STREAM);
			setGZIp(resp);
		}
		else {
			resp->setStatusCode(HttpStatusCode::k404NotFound);
		}

		callback(resp);
	}
};